package com.caesar.gxmz;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;

import java.io.File;

@SuppressLint("JavascriptInterface")
public class MainsActivity extends Activity {
	private WebView webview;
	private boolean isExit;
	private SwipeRefreshLayout swipeLayout;
	private ImageView mainImageView;
	private String indexurl = "http://www.geshow.com/m/";
	private ValueCallback<Uri> mUploadMessage;
	private String mCameraFilePath;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
//		JPushInterface.setDebugMode(false);
//		JPushInterface.init(this);
		SharedPreferences preferences = getSharedPreferences("first",
				Context.MODE_PRIVATE);
		boolean isFirst = preferences.getBoolean("isfrist", true);
		if (isFirst) {
			// createDeskShortCut();
		}
		SharedPreferences.Editor editor = preferences.edit();
		editor.putBoolean("isfrist", false);
		editor.commit();
		webview = (WebView) findViewById(R.id.activity_buy_product_webview);

		// 设置WebView属性，能够执行Javascript脚本
		WebSettings webSettings = webview.getSettings();
		// 设置js可用
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
		webSettings.setSupportZoom(true);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setAllowContentAccess(true);
		webSettings.setAllowUniversalAccessFromFileURLs(true);
		webSettings.setBuiltInZoomControls(false);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		webSettings.setDomStorageEnabled(true);
		webSettings.setDatabaseEnabled(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);

		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		// 添加js调用接口
		webview.addJavascriptInterface(new GoPage(), "goPage");
		webview.loadUrl(indexurl);
		webview.setWebViewClient(new MyWebViewClient());
		webview.setWebChromeClient(new MyWebChromeClient());
		swipeLayout = (SwipeRefreshLayout) findViewById(
				R.id.swipe_container);
		mainImageView = (ImageView) findViewById(
				R.id.main_imageview);
		swipeLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

					@Override
					public void onRefresh() {
						// 重新刷新页面
						webview.loadUrl(indexurl);
						swipeLayout.setRefreshing(false);
					}
				});
	}

	//注入JavaScript的Java类
	class GoPage {
		@JavascriptInterface
		public void onGoPage(String title) {
			ToastUtils.showLong(title);
		}
	}

	@Override
	// 设置回退
	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (webview.canGoBack()) {
				webview.goBack(); // goBack()表示返回WebView的上一页面
				return true;
			} else {
				exit();
			}
		}
		return false;
	}

	private class MyWebChromeClient extends WebChromeClient {
		// 配置权限（同样在WebChromeClient中实现）
		@Override
		public void onGeolocationPermissionsShowPrompt(String origin,
													   GeolocationPermissions.Callback callback) {
			callback.invoke(origin, true, false);
			super.onGeolocationPermissionsShowPrompt(origin, callback);
		}

		// For Android 3.0+
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
									String acceptType) {
			if (mUploadMessage != null) {
				return;
			}
			mUploadMessage = uploadMsg;
			startActivityForResult(createDefaultOpenableIntent(), 1);
		}

		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			openFileChooser(uploadMsg, "");
		}

		// For Android > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
									String acceptType, String capture) {
			openFileChooser(uploadMsg, acceptType);
		}
	}

	private Intent createDefaultOpenableIntent() {
		// Create and return a chooser with the default OPENABLE
		// actions including the camera, camcorder and sound
		// recorder where available.
		Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		i.addCategory(Intent.CATEGORY_OPENABLE);
		i.setType("*/*");

		Intent chooser = createChooserIntent(createCameraIntent(),
				createCamcorderIntent(), createSoundRecorderIntent());
		chooser.putExtra(Intent.EXTRA_INTENT, i);
		return chooser;
	}

	private Intent createChooserIntent(Intent... intents) {
		Intent chooser = new Intent(Intent.ACTION_CHOOSER);
		chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
		chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
		return chooser;
	}

	private Intent createCameraIntent() {
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File externalDataDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		File cameraDataDir = new File(externalDataDir.getAbsolutePath()
				+ File.separator + "browser-photos");
		cameraDataDir.mkdirs();
		mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator
				+ System.currentTimeMillis() + ".jpg";
		cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(mCameraFilePath)));
		return cameraIntent;
	}

	private Intent createCamcorderIntent() {
		return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
	}

	private Intent createSoundRecorderIntent() {
		return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
	}

	// Web视图
	private class MyWebViewClient extends WebViewClient {

		public void openFileChooser(ValueCallback<Uri> uploadFile) {
			// TODO Auto-generated method stub

			if (mUploadMessage != null) {
				return;
			}
			mUploadMessage = uploadFile;
			Intent i = new Intent(Intent.ACTION_GET_CONTENT);
			i.addCategory(Intent.CATEGORY_OPENABLE);
			i.setType("*/*");
			startActivityForResult(
					Intent.createChooser(i, getString(R.string.choose_upload)),
					1);
		}

		@SuppressLint("MissingPermission")
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			if (url.startsWith("tel:")) {
				String[] telNum = url.split("tel:");

				Long num = (long) -1;
				try {
					num = Long.parseLong(telNum[1]);
				} catch (NumberFormatException e) {
					e.printStackTrace();
					num = (long) -1;
				}

				if (num == -1) {
					return true;
				}

				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
						+ telNum[1]));
				startActivity(intent);
				return true;
			} else if (url
					.startsWith("http://www.geshow.com/m/dynamic.php?act=detail&dy_id=")) {
				Intent intent = new Intent(MainsActivity.this,
						ShareActivity.class);
				intent.putExtra("shareUrl", url);
				startActivity(intent);
				return true;
				// 如下方案可在非微信内部WebView的H5页面中调出微信支付
			} else if (url.startsWith("weixin://wap/pay?")) {
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_VIEW);
				intent.setData(Uri.parse(url));
				startActivity(intent);
				return true;
			}
			indexurl = url;
			// oldcode
			// view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
			// oldcode
			// return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			mainImageView.setVisibility( View.GONE );
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
									String description, String failingUrl) {
			// TODO Auto-generated method stub
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
	}

	private void removeCookie() {
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}

	public void exit() {
		if (!isExit) {
			isExit = true;
			Toast.makeText(getApplicationContext(), "再按一次退出程序",
					Toast.LENGTH_SHORT).show();
			mHandler.sendEmptyMessageDelayed(0, 2000);
		} else {
			removeCookie();
			finish();
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			isExit = false;
		}

	};

	@Override
	public void onResume() {
//		JPushInterface.onResume(this);
		super.onResume();

	}

	@Override
	public void onPause() {
//		JPushInterface.onPause(this);
		super.onPause();

	}

	public void createDeskShortCut() {
		Log.i("coder", "------createShortCut--------");
		// 创建快捷方式的Intent
		Intent shortcutIntent = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		// 不允许重复创建
		shortcutIntent.putExtra("duplicate", false);
		// 需要现实的名称
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));
		// 快捷图片
		Parcelable icon = Intent.ShortcutIconResource.fromContext(
				getApplicationContext(), R.drawable.ic_launcher);

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

		Intent intent = new Intent(getApplicationContext(), MainsActivity.class);
		// 下面两个属性是为了当应用程序卸载时桌面 上的快捷方式会删除
		intent.setAction("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.LAUNCHER");
		// 点击快捷图片，运行的程序主入口
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		// 发送广播。OK
		sendBroadcast(shortcutIntent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == 1) {
			if (null == mUploadMessage) {
				return;
			}
			Uri result = data == null || resultCode != RESULT_OK ? null : data
					.getData();
			if (result == null && data == null
					&& resultCode == Activity.RESULT_OK) {
				File cameraFile = new File(mCameraFilePath);
				if (cameraFile.exists()) {
					result = Uri.fromFile(cameraFile);
					// Broadcast to the media scanner that we have a new photo
					// so it will be added into the gallery for the user.
					sendBroadcast(new Intent(
							Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
				}
			}
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}

	}

}
